/*
	实现http server
	http请求地址：/<basepath>/<groupname>/<key>
*/

package geecache

import (
	"fmt"
	"log"
	"net/http"
	"strings"
)

// 默认的basePath为"/_geecache/"
const defaultBasePath = "/_geecache/"

type HTTPPool struct {
	self     string // 记录自己的地址：端口
	basepath string
}

// 新建HTTPPool
// self: 监听地址与端口
func NewHTTPPool(self string) *HTTPPool {
	return &HTTPPool{
		self:     self,
		basepath: defaultBasePath,
	}
}

// Log方法
// 包装log.Printf
func (h *HTTPPool) Log(format string, v ...interface{}) {
	log.Printf("[server - %s]: %s", h.self, fmt.Sprintf(format, v...))
}

// ServeHTTP
func (h *HTTPPool) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 判断路径是否包含basePath
	if !strings.HasPrefix(r.URL.Path, h.basepath) {
		panic("HTTPPool serving unexpected path: " + r.URL.Path)
	}
	h.Log("%s %s", r.Method, r.URL.Path)

	// 分割访问路径，获得groupName和key
	part := strings.SplitN(r.URL.Path[len(h.basepath):], "/", 2)
	if len(part) != 2 {
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}

	groupName := part[0]
	key := part[1]

	// 获取Group
	group := GetGroup(groupName)
	if group == nil {
		http.Error(w, "no such group", http.StatusNotFound)
		return
	}

	// 调用Get
	bv, err := group.Get(key)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// 写返回值
	w.Header().Set("Content-Type", "application/octet-stream")
	w.Write(bv.ByteSlice())
}
